﻿using System;
using Dimebrain.TweetSharp.Core.Extensions;
using Newtonsoft.Json;

namespace Dimebrain.TweetSharp.Model.Twitter.Converters
{
    /// <summary>
    /// Sometimes Twitter returns "0" for "true", instead of true, and we've even seen
    /// "13" for true. For those, and possibly future issues, this converter exists.
    /// </summary>
    public class TwitterWonkyBooleanConverter : TwitterConverterBase
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is string)
            {
                var boolean = value.Equals("0");
                writer.WriteValue(boolean.ToString());
            }

            if (value is Boolean || value is bool?)
            {
                writer.WriteValue(value.ToString());
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }

            var value = reader.Value.ToString();
            var wonkyBool = value.Equals("0")
                                ? true
                                : value.Equals("1")
                                      ? false
                                      : value.TryConvert<bool>();
            return wonkyBool;
        }
        
        public override bool CanConvert(Type objectType)
        {
            var t = (IsNullableType(objectType))
                        ? Nullable.GetUnderlyingType(objectType)
                        : objectType;

            return typeof (Boolean).IsAssignableFrom(t);
        }
    }
}
